<template>
  <div class="video-player">
    <div class="resource-selector">
      <span>第{{ this.videoId }}章 > </span>
      <select
        v-model="selectedResourceId"
        @change="updateSelectedResource"
        class="rounded-border"
      >
        <option
          v-for="resource in resourceData"
          :key="resource.resource_id"
          :value="resource.resource_id"
        >
          {{ resource.resource_title }}
        </option>
      </select>
      <router-link
        :to="{
          name: 'CourseResource',
          params: { unitId: videoId },
        }"
        class="back"
      >
        <img src="@/assets/return.png" alt="" />
        返回
      </router-link>
    </div>
    <div class="video-container">
      <p>{{ selectedResourceTitle }} - {{ resourceType }}</p>
      <div v-if="resourceType === '视频'">
        <div v-if="isLoading" class="loading-overlay">
          <div class="loading-spinner"></div>
          <p>加载中...</p>
        </div>
        <video
          :src="videoUrl"
          controls
          @loadeddata="handleLoadedData"
          @play="handleVideoPlay"
          @pause="handleVideoPause"
          @ended="handleVideoPause"
        ></video>
      </div>
      <div v-else-if="resourceType === '课件'">
        <div v-if="isLoading" class="loading-overlay">
          <div class="loading-spinner"></div>
          <p>加载中...</p>
        </div>
        <iframe
          :src="pptxUrl"
          width="100%"
          height="600px"
          @load="handleIframeLoad"
        ></iframe>
      </div>
      <div v-else>
        <p>资源飞走咯~~qwq</p>
      </div>
    </div>
  </div>
</template>

<script>
import axios from "axios";

export default {
  name: "VideoPlayer",
  props: {
    initialResourceId: {
      type: Number,
      default: null,
    },
  },
  data() {
    return {
      selectedResourceId: this.initialResourceId,
      selectedResourceTitle: "",
      videoUrl: "",
      pptxUrl: "",
      resourceType: "",
      currentProgress: 0,
      resourceData: [],
      watchTime: "00:00:00",
      isLoading: false,
      watchInterval: null,
    };
  },
  created() {
    this.videoId = this.$route.params.videoId;
    this.user_id = localStorage.getItem("userid");
    this.fetchResourceData();
    this.checkCache();
  },
  methods: {
    checkCache() {
      const cacheKey = `resourceData_${this.videoId}`;
      const cachedData = localStorage.getItem(cacheKey);

      if (cachedData) {
        try {
          this.resourceData = JSON.parse(cachedData);
          if (this.selectedResourceId !== null) {
            this.updateSelectedResource();
          }
        } catch (error) {
          //console.error("Error parsing cached data:", error);
          // 如果缓存数据解析失败，重新获取数据
          this.fetchResourceData();
        }
      } else {
        this.fetchResourceData();
      }
    },
    fetchResourceData() {
      fetch(
        `http://8.138.12.59:1999/unit/showresource?unit_id=${this.videoId}`
      )
        .then((response) => response.json())
        .then((data) => {
          this.resourceData = data.data;
          const cacheKey = `resourceData_${this.videoId}`;
          localStorage.setItem(cacheKey, JSON.stringify(this.resourceData));
          this.updateSelectedResource();
        })
        .catch((error) => {
          console.error("Error fetching resource data:", error);
        });
    },
    async updateProgress() {
      try {
        const newAnnouncement = {
          user_id: this.user_id,
          unit_id: this.videoId,
          video_id: this.selectedResourceId,
          watch_time: this.watchTime,
        };
        const response = await axios.post(
          "http://8.138.12.59:1999/resources/watchvideo",
          newAnnouncement
        );
        if (response.data.status === 1) {
          console.log("Progress updated successfully");
        } else {
          throw new Error(`Progress updated 失败: ${response.status}`);
        }
        // 处理成功后的逻辑（如果需要）
      } catch (error) {
        console.error("Error updating progress:", error);
      }
    },
    async updateResourceCheckStatus(resourceId) {
      try {
        const newAnnouncement = {
          resource_id: resourceId,
          user_id: this.user_id,
          unit_id: this.videoId,
        };
        const response = await axios.post(
          "http://8.138.12.59:1999/resources/addStuResource",
          newAnnouncement
        );

        if (response.data.status === 1) {
          // 请求成功
          console.log(this.selectedResourceTitle + "Click");
        } else {
          throw new Error(`Upodata fault: ${response.status}`);
        }
      } catch (error) {
        console.error("Error updating resource check status:", error);
      }
    },
    updateSelectedResource() {
      const selectedResource = this.resourceData.find(
        (resource) => resource.resource_id === parseInt(this.selectedResourceId)
      );
      if (selectedResource) {
        this.selectedResourceTitle = selectedResource.resource_title;
        this.resourceType = this.getResourceType(
          selectedResource.resource_type
        );

        this.isLoading = true;

        if (this.resourceType === "视频") {
          this.videoUrl = selectedResource.url;
          this.pptxUrl = "";
        } else if (this.resourceType === "课件") {
          this.pptxUrl = `https://view.officeapps.live.com/op/view.aspx?src=${encodeURIComponent(
            selectedResource.url
          )}`;
          this.videoUrl = "";
          this.handleIframeLoad = () => {};
        }
        this.isLoading = false;
        this.updateResourceCheckStatus(this.selectedResourceId);
      }
    },
    getResourceType(resourceType) {
      switch (resourceType) {
        case "video":
          return "视频";
        case "ppt":
          return "课件";
        default:
          return resourceType;
      }
    },
    handleVideoPlay() {
      this.startWatchTime();
    },
    handleVideoPause() {
      this.stopWatchTime();
    },
    handleLoadedData() {
      this.isLoading = false;
    },
    handleIframeLoad() {
      this.isLoading = false;
    },
    startWatchTime() {
      this.watchTime = "00:00:00";
      let seconds = 0;

      this.watchInterval = setInterval(() => {
        seconds += 1;
        const hours = Math.floor(seconds / 3600);
        const minutes = Math.floor((seconds % 3600) / 60);
        const secs = seconds % 60;
        this.watchTime = `${String(hours).padStart(2, "0")}:${String(
          minutes
        ).padStart(2, "0")}:${String(secs).padStart(2, "0")}`;
      }, 1000);
    },
    stopWatchTime() {
      clearInterval(this.watchInterval);
    },
  },
  mounted() {
    window.addEventListener("beforeunload", this.updateProgress());
  },
  beforeUnmount() {
    window.removeEventListener("beforeunload", this.updateProgress());
    this.stopWatchTime();
  },
};
</script>

<style>
.video-player {
  background-color: #f9f9f9;
  padding: 20px 10%;
}

.content {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.resource-selector {
  padding: 20px 20px 0px 20px;
  text-align: left;
}

.rounded-border {
  border-radius: 8px;
  border: 1px solid #3b96ff;
  padding: 8px;
  font-size: 16px;
}

p {
  padding-bottom: 20px;
  color: #3b96ff;
}

.back {
  padding-left: 20px;
  text-decoration: none;
  color: #3b96ff;
}

.loading-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(255, 255, 255, 0.8);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1;
}

.loading-spinner {
  border: 4px solid rgba(0, 0, 0, 0.1);
  width: 36px;
  height: 36px;
  border-radius: 50%;
  border-left-color: #09f;
  animation: spin 1s ease infinite;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

.video-container {
  position: relative;
}

video,
iframe {
  width: 100%;
  height: 600px;
}
</style>
